package com.os.concurrent;

import java.util.concurrent.*;

public class MyTestFeature {

    public void doSomethingElse(){
        try {
            System.out.println("do something else start...");
            Thread.sleep(10000);
            System.out.println("do something else end...");
        }catch (InterruptedException e){
            throw new RuntimeException();
        }
    }

    public void testFeature(){
        //执行服务
        ExecutorService executorService = Executors.newCachedThreadPool();
        //异步任务结果
        Future<Double> future = executorService.submit(new Task());

        //异步操作进行的同时，可以进行其他操作
        doSomethingElse();

        try {
            //获取异步操作的结果，如果最终被阻塞，无法得到结果，那么再最多等待5秒之后退出
            Double result = future.get(5, TimeUnit.SECONDS);
            System.out.println("result: " + result);
        }catch (ExecutionException e){
            //计算抛出一个异常
            e.printStackTrace();
        }catch (InterruptedException e){
            //当前线程等待过程中被中断
            System.out.println("interrupted!");
        }catch (TimeoutException e){
            //在future对象完成之前超过已过期
            System.out.println("timeoutException");
        }
        executorService.shutdown();
    }

    public static void main(String[] args) {
        MyTestFeature myTestFeature = new MyTestFeature();
        myTestFeature.testFeature();
    }
}
